#include "LoadingScene.h"
#include "MainMenuScene.h"
#include "SimpleAudioEngine.h"

USING_NS_CC;
using namespace CocosDenshion;

LoadingScene::LoadingScene():
	__winSize(),
	__pProgressBar(NULL),
	__loadingLabel(NULL),
	__numberOfLoadedResources(0.0f),
	__numberOfResources(0.0f)
{}

CCScene*
LoadingScene::scene()
{
	// 'pScene' is an autorelease object
	CCScene* pScene = CCScene::create();

	// 'pLayer' is an autorelease object
	LoadingScene* pLayer = LoadingScene::create();

	// add the layer as a child to the scene
	pScene->addChild(pLayer);
	return pScene;
}

bool
LoadingScene::init()
{
	if(!CCLayer::init())
	{
		return false;
	}

	__winSize = CCDirector::sharedDirector()->getWinSize();

	// Create the background sprite.
	CCSprite* background = CCSprite::spriteWithFile("scoresBackground.png");
	background->setPosition(ccp(__winSize.width / 2.0f, __winSize.height / 2.0f));
	float scaleX = __winSize.width/ background->getTextureRect().size.width;
	float scaleY = __winSize.height/ background->getTextureRect().size.height;
	background->setScaleX(scaleX);
	background->setScaleY(scaleY);
	this->addChild(background, -1);

	CCSprite* progressBarBackground = CCSprite::spriteWithFile("loadingBarBackground.png");
	progressBarBackground->setPosition(ccp(__winSize.width / 2.0f, __winSize.height / 2.0f));
	this->addChild(progressBarBackground);

	CCSprite* pSprite = CCSprite::spriteWithFile("loadingBar.png");
	__pProgressBar = CCProgressTimer::progressWithSprite(pSprite);
	__pProgressBar->setType(CCProgressTimerType::kCCProgressTimerTypeBar);
	CCSize barSize = __pProgressBar->getContentSize();
	__pProgressBar->setPosition(progressBarBackground->getPosition());
	this->addChild(__pProgressBar);

	__loadingLabel = CCLabelTTF::labelWithString("Loading...", "Sansation_Bold.ttf", 40.0f);
	__loadingLabel->setPosition(ccp(__winSize.width / 2.0f, __winSize.height / 2.0f + 30.0f));
	this->addChild(__loadingLabel);

	__numberOfLoadedResources = 0;
	__numberOfResources = 6;//nhandt

	schedule(schedule_selector(LoadingScene::updateLoadingLabel), 1.0f);

	return true;
}

/**
 * Update the progress bar and change scene if loading has finished.
 */
void
LoadingScene::resourceLoadedCallback(cocos2d::CCObject* obj)
{
	__numberOfLoadedResources++;

	float progress = (__numberOfLoadedResources / __numberOfResources) * 100.0f;
	updateProgress(progress);

	if(progress == 100.0f)
	{
		//Load sprite sheets descriptions
		/*
		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("ShipAndHud.plist");
		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("background.plist", "background.png");
		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("SpaceLevel1.plist");
		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("SpaceLevel2.plist");
		*/
		CCScene *pMenuScene = MainMenuScene::scene();
		CCDirector::sharedDirector()->replaceScene(pMenuScene);
	}
}

void
LoadingScene::onEnter()
{
	CCLayer::onEnter();
	CCDictionary* sounds = CCDictionary::dictionaryWithContentsOfFile("sounds.plist");

	preloadSoundFile(sounds->objectForKey("enemyExplosion"),true);
	preloadSoundFile(sounds->objectForKey("shipExplosion"),true);
	preloadSoundFile(sounds->objectForKey("bombExplosion"),true);
	preloadSoundFile(sounds->objectForKey("bombShot"),true);
	preloadSoundFile(sounds->objectForKey("standardShot"),true);
	preloadSoundFile(sounds->objectForKey("backgroundMusic"), true);
	/*
	CCTextureCache::sharedTextureCache()->addImageAsync("ShipAndHud.png", this, callfuncO_selector(LoadingScene::resourceLoadedCallback));
	
	CCTextureCache::sharedTextureCache()->addImageAsync("SpaceLevel1.png", this, callfuncO_selector(LoadingScene::resourceLoadedCallback));
	CCTextureCache::sharedTextureCache()->addImageAsync("SpaceLevel2.png", this, callfuncO_selector(LoadingScene::resourceLoadedCallback));
	*/
	CCTextureCache::sharedTextureCache()->addImageAsync("background.png", this, callfuncO_selector(LoadingScene::resourceLoadedCallback));
}

void
LoadingScene::updateProgress(float progress)
{
	__pProgressBar->setPercentage(progress);
}

/**
 * Update the loading label by changing the number of dots following the "Loading" word.
 */
void
LoadingScene::updateLoadingLabel(float dt)
{
	static int i = 0;

	const int labelLength = 11;
	char loadingLabelText[labelLength];
	sprintf(loadingLabelText, "Loading%c%c%c", i > 0 ? '.' : ' ', i > 1 ? '.' : ' ', i > 2 ? '.' : ' ');
	__loadingLabel->setString(loadingLabelText);

	i++;
	if(i > 3)
	{
		i = 0;
	}
}

/**
 * @param fileName This should be equal to the value returned by the objectForKey() method of CCMutableDictionary.
 * @param musicFile If true, the fileName indicates a music file which is preloaded differently to an effect file.
 */
void
LoadingScene::preloadSoundFile(CCObject* fileName, bool musicFile)
{
	CCString* fileNameCCString = static_cast<CCString*>(fileName);
	const char* fileNameStdString = fileNameCCString->getCString();
	if(musicFile)
	{
		SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(fileNameStdString));
	}
	else
	{
		SimpleAudioEngine::sharedEngine()->preloadEffect(CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(fileNameStdString));
	}
	resourceLoadedCallback();
}

